package org.bonorsoft.modules.wechat.controller;

import com.alibaba.fastjson.JSONObject;
import org.bonorsoft.common.util.WxUtil;
import org.bonorsoft.modules.wechat.entity.JsCode;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wechat")
public class WxConfigController {

    @GetMapping(value = "/jscodeToSession")
    public Map<String, Object> jscodeToSession(JsCode code) {//js_code 登录(wx.login())时获取的 code
        Map<String, Object> reMap = new HashMap<>();
        String v_appid = code.getAppid();
        String v_secret = code.getSecret();
        String js_code = code.getJs_code();
        System.out.println(code);
        /*String v_appid = "wxc75bb1b17e911a20";
        String v_secret = "299ebe9497552b32b8360650752cc190";*/
        /*String v_appid = "wx1dfd64bbdde79997";
        String v_secret = "ae3757ec0a23c1f69acda3456e52506a";*/
        String readInterFaceFromUrlByUTF8 = WxUtil.readInterFaceFromUrlByUTF8("https://api.weixin.qq.com/sns/jscode2session?appid=" + v_appid + "&secret=" + v_secret + "&js_code=" + js_code + "&grant_type=authorization_code");
        JSONObject root = JSONObject.parseObject(readInterFaceFromUrlByUTF8);
        JSONObject data = new JSONObject();
        if (root.containsKey("errcode")) {
            reMap.put("success", false);
            data.put("errcode", root.getString("errcode"));
            data.put("errmsg", root.getString("errmsg"));
            reMap.put("data", data);
        } else {
            reMap.put("success", true);
            data.put("session_key", root.getString("session_key"));
            data.put("openid", root.getString("openid"));
            data.put("unionid", root.getString("unionid"));
            reMap.put("data", data);
        }
        return reMap;
    }

    @PostMapping(value = "/getPhoneNumber")
    public Map<String, Object> getPhoneNumber(String session_key, String encryptedData, String iv) {
        Map<String, Object> reMap = new HashMap<>();
        String v_result = WxUtil.analysisPhoneNumber(session_key, encryptedData, iv);
        JSONObject resultObject = JSONObject.parseObject(v_result);
        reMap.put("phoneNumber", resultObject.getString("phoneNumber"));
        reMap.put("purePhoneNumber", resultObject.getString("purePhoneNumber"));
        reMap.put("countryCode", resultObject.getString("countryCode"));//国家代码
        System.out.println(reMap);
        return reMap;
    }
}
